<template>
  <div class="informationPag">
    <div class="basicInfo front-color">
      <h1>{{$t('myAdd.personalInfo.baseInfo')}}</h1>
      <div class="user_reg_info clearfix">
        <div class="headImg pointer" @click="upload">
          <div class="border" v-if="!ownWantedList.imageUrl">
            <i class="icon-personal-default"></i>
          </div>
          <img v-else :src="ownWantedList.imageUrl" alt="">
          <div class="camera">
            <i class="icon-camera"></i>
          </div>
          <div class="ifbusiness" v-if="ifbusiness">
            <span class="icon-icon">
              <span class="path1"></span>
              <span class="path2"></span>
              <span class="path3"></span>
            </span>
          </div>
        </div>
        <div class="user_reg_info_text">
          <div class="top clearfix">
            <div class="top_account">
              <span class="top_account_name">{{$t('myAdd.personalInfo.regAccount')}}</span><br/>
              <span class="top_account_cont">{{userInfo.userAccount}}</span>
            </div>
            <div class="top_uid">
              <span class="top_uid_name">UID</span><br/>
              <span class="top_uid_cont">{{userInfo.id}}</span>
            </div>
          </div>
          <div class="bottom">
            <div class="bottom_title"><span>{{$t('myAdd.personalInfo.nickName')}}</span></div>
            <div class="bottom_cont">
              <input
                v-show="editNickNameStatus"
                type="text"
                class="edit-name-input"
                ref="editNickNameinput"
                v-model="nickName"
                @input = "handleEditNickName('input', $event.target.value)"
                @keyup.enter="editNickName"
              />
              <span v-show="!editNickNameStatus">{{nickName}} </span>
              <span @click="editNickName" class="pointer">
                <i class="icon-edit-2" v-if="!editNickNameStatus"></i>
                <span v-else>{{editNameBtn}}</span>
              </span>
            </div>
            <p class="changeNickName">* {{$t('myAdd.personalInfo.changeNickNameTip')}}</p>
          </div>
        </div>
      </div>
    </div>
    <!-- 实名认证 -->
    <div class="realName front-color">
      <h1>{{$t('myAdd.personalInfo.realName')}}</h1>
      <div class="toReal clearfix">
        <div class="real_info">
          <p class="real_info_text" v-if="userInfo.authNewLevel !== 'C0'"><span>{{$t('myAdd.personalInfo.personalCerti')}}_*</span><span>{{userInfo.certificateName}}</span></p>
          <p class="real_info_num">{{showCertificateNumber}}</p>
        </div>
        <div class="real_entrance clearfix">
          <div class="primary">
            <p class="text"><i class="icon-true_icon" v-if="userInfo.authNewLevel !== 'C0'"></i><i v-else class="icon-uniE910"></i>{{$t('myAdd.personalInfo.primaryCert')}}</p>
            <p class="textBtn pointer"><span v-if="userInfo.authNewLevel === 'C0'" @click="toInfoAttestation">{{$t('myAdd.personalInfo.toVerity')}}</span></p>
          </div>
          <div class="guide">
            <p class="ico"><i class="icon-arrow-right"></i></p>
            <p></p>
          </div>
          <div class="advanced">
            <P class="text">
              <i class="icon-true_icon" v-if="userInfo.authNewLevel === 'C2'"></i>
              <i v-else class="icon-uniE910"></i>{{$t('myAdd.personalInfo.advancedVerity')}}
            </P>
            <P class="textBtn pointer">
              <span v-if="userInfo.authNewLevel !== 'C2' && userInfo.authNewLevel === 'C1' && userInfo.authLevel === 3" @click="toInfoAttestation">{{$t('myAdd.personalInfo.toVerity')}}</span>
              <span v-if="userInfo.authLevel === 0">{{$t('myAdd.personalInfo.underReview')}}</span>
              <span v-if="userInfo.authLevel === 2" @click="toInfoAttestation">{{$t('myAdd.personalInfo.noPass')}}</span>
            </P>
          </div>
        </div>
      </div>
    </div>
    <elDialog :flag='uplShow' :title='uploadTile' :width='620' :dialogClose='portraits'>
      <div slot="operation" class="uploadTitle">
        {{uploadTile}}
      </div>
      <div slot="content" class="img_btn clearfix">
        <div class="showImg">
          <cropper ref="cropper" :headImg="ownWantedList.imageUrl" :reUploadBtnText="reUploadBtnText" :uploading="uploading"></cropper>
        </div>
      </div>
      <div slot="options">
        <button @click="portraits" class="cancel">{{$t('myAdd.personalInfo.cancel')}}</button>
        <button  @click="crop" :class="{rate: !uploading}" class="saveHeadImgBtn">{{$t('myAdd.personalInfo.save')}}</button>
      </div>
    </elDialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import elDialog from '@/components/common/addCommon/dialog'
import coinImg from '@/assets/img/otc/portrait.png'
import cropper from '@/components/addPage/common/cropper'
import eventBus from '../../apis/bus'  // 引入bus

let pat = new RegExp('[^a-zA-Z0-9_\u4e00-\u9fa5]', 'i') // 检测非法字符

export default {
  name: 'information',
  components: { elDialog, cropper },
  data () {
    return {
      uid: null,
      certificateNumber: null,
      showCertificateNumber: null,
      nickName: null,
      ifbusiness: 0,
      editNickNameStatus: false,
      editThrough: true, // 用来存储修改昵称是否合规的状态
      uplShow: false,
      uploadTile: this.$t('myAdd.personalInfo.editHeadImg'),
      clibut: false,
      ownWantedList: {}, // 存储用户信用度 历史交易额信息
      imgSrc: coinImg, // 默认头像
      uploading: true,
      previewImg: null,
      userNickNameErrTip: ''
    }
  },
  computed: {
    ...mapState({
      userInfo ({baseData: {_user}}) {
        if (_user) {
          this.uid = _user.id
          this.nickName = _user.nickName
          this.certificateNumber = _user.certificateNumber
          this.ifbusiness = _user.ifbusiness
          return _user
        } else {
          return false
        }
      }
    }),
    Internationalization () {
      return {
        editHeadImg: this.$t('myAdd.personalInfo.editHeadImg'),
        reUpload: this.$t('myAdd.personalInfo.reUpload'),
        uoloading: this.$t('myAdd.personalInfo.uploading'),
        confirm: this.$t('myAdd.personalInfo.confirm'),
        canNotLessThanFour: this.$t('myAdd.personalInfo.canNotLessThanFour'), // 昵称长度不能小于4位
        changeNickName: this.$t('myAdd.personalInfo.changeNickName') // 昵称不能含有非法字符
      }
    },
    reUploadBtnText () {
      return this.uploading ? this.Internationalization.reUpload : this.Internationalization.uoloading
    },
    editNameBtn () {
      return this.Internationalization.confirm
    }
  },
  mounted () {
    eventBus.$on('postImg', (val) => {
      this.uploads(val)
    })
  },
  watch: {
    'certificateNumber' (newVal) {
      if (newVal) {
        let certificateNumber = newVal
        certificateNumber = /^(.{4})(.*)(.{4})$/.exec(certificateNumber)
        let star = ''
        for (let i = 0; i < certificateNumber[2].length; i++) {
          star += '*'
        }
        this.showCertificateNumber = certificateNumber[1] + star + certificateNumber[3]
      }
    },
    '$store.state.baseData._lan' (val) {
      // 监听语言的变化
      this.uploadTile = this.Internationalization.editHeadImg
    },
    uid () {
      this.getUserWanted()
    }
  },
  methods: {
    editNickName () {
      if (!this.editNickNameStatus) {
        this.editNickNameStatus = true
      } else {
        // START 胖虎新增修改昵称的判断限制
        if (!this.editThrough) {
          this.$store.dispatch('setTipState', {text: this.userNickNameErrTip, type: 'error'})
          return false
        }
        // END 胖虎新增修改昵称的判断限制
        let newValue = this.$refs.editNickNameinput.value
        if (!newValue) {
          return false
        } else if (newValue !== this.userInfo.nickName) {
          this.axios({
            url: this.$store.state.url.personal.nickname_update,
            headers: {},
            params: {nickname: newValue},
            method: 'post'
          }).then((data) => {
            this.editNickNameStatus = false
            this.$store.dispatch('getCommonUser_info')
          })
        }
      }
    },
    handleEditNickName (type, val) {
      val = val.trim()
      this.nickName = isNaN(Number(val.trim()[0])) ? val : ''
      this.nickName = this.nickName.length > 12 ? this.nickName.substring(0, 12) : this.nickName
      if (this.nickName.length < 4) {
        this.userNickNameErrTip = this.Internationalization.canNotLessThanFour
        this.editThrough = false
        return false
      }
      this.editThrough = this.nickName.length >= 4 && !pat.test(val) ? true : false, this.userNickNameErrTip = this.Internationalization.changeNickName
    },
    // 去实名认证页面
    toInfoAttestation () {
      this.$router.push({
        path: '/personal/infoAttestation'
      })
    },
    // 上传头像
    upload () {
      this.uplShow = true
    },
    // 关闭上传头像弹窗
    portraits () {
      this.uplShow = false
      this.clibut = false
    },
    // 上传到后台
    uploads (file) {
      if (file) {
        let _from = new FormData()
        _from.append('file', file, 'image.png')
        this.axios({
          url: '/common/upload_img',
          headers: {'Content-Type': 'multipart/form-data'},
          params: _from,
          method: 'post'
        }).then(res => {
          if (res.code.toString() === '0') {
            if (res.data.filenameStr) {
              this.imageDataStr = res.data.filenameStr
            } else {
              this.imageDataStr = res.data.filename
            }
            this.$store.dispatch('setTipState', this.$t('user.questions.upload_success'))
            this.clibut = true
            this.picture()
          } else {
            this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
          }
        })
      }
    },
    // 保存头像
    picture () {
      if (this.clibut) {
        this.axios({
          url: this.$store.state.otcUrl.common.upload_img,
          params: {
            imgURL: this.imageDataStr
          },
          hostType: 'otc',
          method: 'post'
        }).then((data) => {
          if (data.code.toString() === '0') {
            this.uploading = true
            this.uplShow = false
            this.getUserWanted()
            this.clibut = false
          }
        })
      }
    },
    // 获取用户的信用度 历史成交等信息
    getUserWanted () {
      this.axios({
        url: this.$store.state.otcUrl.personal.person_home_page,
        headers: {},
        params: {
          uid: this.uid.toString()
        },
        hostType: 'otc',
        method: 'post'
      }).then(data => {
        if (data.code.toString() === '0') {
          this.ownWantedList = data.data
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 触发cropper组件的crop事件
    crop () {
      if (!this.uploading) {
        return false
      }
      this.$refs.cropper.crop()
      this.uploading = false
    }
  }
}
</script>
